<template>
    <div class="box">
        <div class="clearfix" v-show="showHide1">
            <el-container>
                <div class="mostTop"></div>
                <el-header class="clearfix">
                    <p class="allBook">所有图书</p>
                    <p class="allBookRoute"><span @click="goHome()">首页</span> > 所有图书</p>
                </el-header>
                <div class="btnPart clearfix">
                    <el-button type="primary" @click="del()">删除选择</el-button>
                    <el-button type="success" @click="reloaded()">刷新</el-button>
                    <el-select v-model="value" placeholder="选择学科" class="selectClass" @change="searchCourse()">
                        <el-option
                                v-for="item in options"
                                :key="item.id"
                                :label="item.courseName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                    <el-input
                            placeholder="请输入图书名称"
                            v-model="input"
                            clearable
                            class="bookInp">
                    </el-input>
                    <el-button type="primary" icon="el-icon-search" @click="searchBook()">搜素</el-button>
                    <el-button type="success" class="btnRight" @click="goAdd()">新增图书</el-button>
                </div>
                <!--表格内容-->
                <el-main>
                    <div>
                        <el-table
                                ref="multipleTable"
                                :data="tableData"
                                tooltip-effect="dark"
                                style="width: 100%"
                                @selection-change="handleSelectionChange"
                        >
                            <el-table-column
                                    type="selection"
                                    style="width:10%">
                            </el-table-column>
                            <el-table-column
                                    prop="bookName"
                                    label="图书名称"
                                    style="width:25%">
                            </el-table-column>
                            <el-table-column
                                    prop="courseName"
                                    label="学科"
                                    style="width:10%">
                            </el-table-column>
                            <el-table-column
                                    prop="author"
                                    label="作者名称"
                                    style="width:15%"
                            >
                            </el-table-column>
                            <el-table-column
                                    prop="bookPublish"
                                    label="出版社"
                                    style="width:20%"
                                    show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column
                                    prop="price"
                                    label="价格(元)"
                                    style="width:10%"
                                    show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column
                                    prop="collectedDate"
                                    label="录入时间"
                                    style="width:10%"
                                    show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column
                                    prop="option"
                                    label="操作"
                                    style="width:5%"
                                    show-overflow-tooltip>
                                <template slot-scope="scope">
                                    <el-button type="text" @click="edit(scope.$index, scope.row)">编辑</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-main>

            </el-container>
            <!--分页-->
            <el-pagination
                    :page-size="10"
                    layout="prev, pager, next"
                    :total="total"
                    @current-change="handleCurrentChange"
                    :current-page.sync="currentPage">
            </el-pagination>
            <!--page-size:每页显示条目个数
                pager-count：页码按钮的数量，当总页数超过该值时会折叠
                total	总条目数
            -->
        </div>
        <div class="edit" v-show="showHide2">
            <el-container>
                <div class="mostTop"></div>
                <el-header class="clearfix">
                    <p class="addBookTitle">编辑图书</p>
                    <p class="return" @click="cancel()">< 返回</p>
                </el-header>
                <el-main>
                    <p class="bookDetails">基本信息</p>
                    <div class="inputTitle clearfix">
                        <div class="left">
                            <p>图书名称</p>
                            <el-input v-model="bookName" placeholder="图书名称"></el-input>
                            <p>所属课程</p>
                            <el-select v-model="courseName" placeholder="请选择">
                                <el-option
                                        v-for="item in options"
                                        :key="item.id"
                                        :label="item.courseName"
                                        :value="item.id"
                                >
                                </el-option>
                            </el-select>
                            <p>图书价格</p>
                            <el-input v-model="price" placeholder="图书价格"></el-input>
                        </div>
                        <div class="right">
                            <p>图书作者</p>
                            <el-input v-model="author" placeholder="图书作者"></el-input>
                            <p>出版社</p>
                            <el-input v-model="bookPublish" placeholder="出版社"></el-input>
                        </div>
                    </div>
                </el-main>
            </el-container>
            <div id="footBox">
                <div id="footer">
                    <el-button type="info" @click="cancel()">取消</el-button>
                    <el-button type="success" @click="ok()">保存</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: "BooksList",
        data() {
            return {
                currentPage: 1,//当前显示页面页码
                total: 0,//图书数组总数
                bookName: '',//图书名称回显
                price: '',//图书价格回显
                author: '',//图书作者回显
                bookPublish: '',//图书出版社回显
                courseId: '',//课程id用于编辑后保存时向后端传数据
                id: '',//图书id用于编辑后保存时向后端传数据
                input: '',//搜索框内容
                options: '',//编辑里面的课程选择下拉菜单
                courseName: '',//编辑里面回显input框内容
                value: '',//搜索下拉菜单input框内容
                tableData: [],//图书列表内容
                multipleSelection: [],//存选择要删除图书的id
                showHide1: true,
                showHide2: false,
            }
        },
        methods: {
            //分页切换
            handleCurrentChange: function (currentPage) {
                this.currentPage = currentPage;
                if (!this.input && !this.value) {
                    this.Rendering()
                } else if (!this.input && this.value) {
                    this.searchCoursePack()
                } else if (this.input && !this.value) {
                    this.searchBookPack()
                } else if (this.input && this.value) {
                    this.searchCourseAndBookPack()
                }
            },
            //列表模式多选删除id获取
            handleSelectionChange(val) {
                var selected = [];
                for (var i = 0; i < val.length; i++) {
                    selected.push(val[i].id)
                }
                this.multipleSelection = selected;
                //console.log(this.multipleSelection);
            },
            //多选删除
            del() {
                if (this.multipleSelection == '') {
                    this.$message({
                        type: 'warning',
                        message: '请选择需删除图书'
                    });
                } else {
                    this.$confirm('此操作将永久删除所选图书, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.$axios({
                            method: 'post',
                            url: '/book/delete',
                            data: {
                                ids: this.multipleSelection
                            },
                        }).then((res) => {
                            //console.log(res)
                            if (res.data.msg == '操作成功') {
                                this.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                });
                                this.Rendering();
                            } else {
                                this.$message({
                                    type: 'err',
                                    message: '删除失败'
                                });
                            }
                        });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                }

            },
            //根据课程搜索函数封装
            searchCoursePack() {
                this.input = '';
                if (!this.input) {
                    for (var i = 0; i < this.options.length; i++) {
                        if (this.options[i].courseName == this.value) {
                            this.value = this.options[i].id
                        }
                    }
                    //console.log(this.value);
                    this.$axios({
                        url: '/book/list',
                        params: {
                            page: this.currentPage,
                            courseId: this.value,
                            limit: 10,
                        },
                    }).then((res) => {
                        var data = res.data.data.list;
                        //console.log(data)
                        for (var i = 0; i < data.length; i++) {
                            data[i].collectedDate = this.format(data[i].collectedDate)
                        }
                        //console.log(res);
                        this.tableData = data;
                        this.total = res.data.data.total;
                        //console.log(this.total);
                    })
                }
            },
            //根据课程搜索
            searchCourse() {
                this.searchCoursePack()
            },
            //根据书名搜索函数封装
            searchBookPack() {
                if (this.input && !this.value) {
                    this.$axios({
                        url: '/book/list',
                        params: {
                            page: this.currentPage,
                            bookName: this.input,
                            limit: 10,
                        },
                    }).then((res) => {
                        var data = res.data.data.list;
                        //console.log(data)
                        for (var i = 0; i < data.length; i++) {
                            data[i].collectedDate = this.format(data[i].collectedDate)
                        }
                        //console.log(res);
                        this.tableData = data;
                        this.total = res.data.data.total;
                        //console.log(this.total);
                    })
                } else if (this.input && this.value) {
                    this.searchCourseAndBookPack()
                }
            },
            //根据书名搜索
            searchBook() {
                this.searchBookPack()
            },
            //封装根据部门和书名一起搜索
            searchCourseAndBookPack() {
                this.$axios({
                    url: '/book/list',
                    params: {
                        page: this.currentPage,
                        limit: 10,
                        courseId: this.value,
                        bookName: this.input,
                    },
                }).then((res) => {
                    var data = res.data.data.list;
                    //console.log(data)
                    for (var i = 0; i < data.length; i++) {
                        data[i].collectedDate = this.format(data[i].collectedDate)
                    }
                    //console.log(res);
                    this.tableData = data;
                    this.total = res.data.data.total;
                    //console.log(this.total);
                })
            },
            //刷新
            reloaded() {
                location.reload();
            },
            //去首页
            goHome() {
                this.$router.push({path: '/index'})
            },
            //封装渲染编辑页面下拉菜单所有课程
            select() {
                this.$axios({
                    url: '/course/allName',
                    method: 'get'
                }).then((res) => {
                    //console.log(res.data.data);
                    this.options = res.data.data;
                    //console.log(this.options)
                });
            },
            //编辑
            edit(index, row) {
                //console.log(row.id);
                this.showHide1 = !this.showHide1;
                this.showHide2 = !this.showHide2;
                //渲染编辑页面下拉菜单所有课程
                this.select();
                //编辑回显
                this.$axios({
                    url: `/book/desc/${row.id}`,
                    params: row.id
                }).then((res) => {
                    //console.log(res);
                    this.bookName = res.data.data.bookName;
                    this.courseName = res.data.data.courseName;
                    this.price = res.data.data.price;
                    this.author = res.data.data.author;
                    this.bookPublish = res.data.data.bookPublish;
                    this.courseId = res.data.data.courseId;
                    this.id = res.data.data.id;
                })
            },
            //编辑里面的保存按钮
            ok() {
                var reg = /^[0-9]*$/;
                if (this.bookPublish == '') {
                    this.$message({
                        type: 'error',
                        message: '请填写该书出版社'
                    });
                } else if (!reg.test(this.price)) {
                    this.$message({
                        type: 'error',
                        message: '价格请填写数字'
                    });
                } else if (this.price == '') {
                    this.$message({
                        type: 'error',
                        message: '请填写该书价格'
                    });
                } else if (this.author == '') {
                    this.$message({
                        type: 'error',
                        message: '请填写该书作者'
                    });
                } else if (this.bookName == '') {
                    this.$message({
                        type: 'error',
                        message: '请填写该书名称'
                    });
                } else {
                    this.$axios({
                        method: 'post',
                        url: '/book/update',
                        data: {
                            author: this.author,
                            bookImage: null,
                            bookName: this.bookName,
                            bookPublish: this.bookPublish,
                            courseId: this.courseId,
                            id: this.id,
                            price: this.price,

                        }
                    }).then((res) => {
                        console.log(res);
                        if (res.data.msg == '必须小于或等于999.99' || res.data.msg == '必须大于或等于0.01') {
                            this.$message({
                                type: 'error',
                                message: '价格' + res.data.msg
                            });
                        } else if (res.data.msg == 'success') {
                            this.$message({
                                type: 'success',
                                message: '修改成功'
                            });
                            this.leave();
                            location.reload();
                        }
                    }).catch((err) => {

                    });
                }

            },
            //离开编辑页到图书列表
            leave() {
                this.showHide2 = !this.showHide2;
                this.showHide1 = !this.showHide1
            },
            //编辑里面的取消按钮
            cancel() {
                this.$confirm('此操作将离开本页面，修改内容未保存, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$message({
                        type: 'success',
                        message: '取消成功!'
                    });
                    this.showHide2 = !this.showHide2;
                    this.showHide1 = !this.showHide1
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消离开!'
                    });
                });

            },
            goAdd() {
                this.$router.push({path: '/AddBook'})
            },
            //补零规则
            add0(m) {
                return m < 10 ? '0' + m : m
            },
            //将时间戳转换为日期格式
            format(shijianchuo) {
                //时间戳是整数，否则要parseInt转换
                var time = new Date(shijianchuo);
                var y = time.getFullYear();
                var m = time.getMonth() + 1;
                var d = time.getDate();
                return y + '-' + this.add0(m) + '-' + this.add0(d) + ' ';
            },
            //请求图书列表接口封装
            Rendering() {
                this.$axios({
                    url: '/book/list',
                    params: {
                        page: this.currentPage,
                        limit: 10,
                    },
                }).then((res) => {
                    if (res.data.code == 0) {
                        var data = res.data.data.list;
                        //console.log(data)
                        for (var i = 0; i < data.length; i++) {
                            data[i].collectedDate = this.format(data[i].collectedDate)
                        }
                        this.tableData = data;
                        //console.log(res.data.data);
                        this.total = res.data.data.total;
                    } else {
                        this.$router.push("/noResponse");
                        if (res.data.code == 0) {
                            this.$router.push("/administrator");
                        }
                    }
                })
            }
        },
        mounted() {
            //渲染页面
            this.Rendering();
            //渲染搜索按钮前面下拉菜单所有课程
            this.select()
        }
    }
</script>

<style scoped lang="less">
    .clearfix:after {
        content: '';
        clear: both;
        display: block;
    }

    li {
        list-style: none;
    }

    .mostTop {
        height: 10px;
        background: #f2f2f6;
    }

    .el-header {
        background-color: #fff;
        margin-top: 10px;
        line-height: 30px;

        .allBook {
            color: #333;
            float: left;
            font-size: 18px;
        }

        .allBookRoute {
            color: #333;
            float: right;
            font-size: 18px;

            span:hover {
                color: #8cc5ff;
                cursor: pointer;
            }
        }
    }

    .btnPart {
        padding: 10px;
        background: #f2f2f6;
        margin: 10px;

        .selectClass {
            margin-left: 10px;
        }

        .bookInp {
            display: inline-block;
            width: 200px;
        }
    }

    .btnRight {
        float: right;
    }

    .el-pagination {
        float: right;
    }

    .edit {
        .el-header {
            background-color: #fff;
            margin-top: 10px;
            line-height: 30px;

            .addBookTitle {
                color: #333;
                float: left;
                font-size: 18px;
            }

            .return {
                color: #333;
                float: right;
                font-size: 18px;
                cursor: pointer;
            }

            .return:hover {
                color: #8cc5ff;
            }
        }

        .el-main {
            margin-top: 10px;
            background-color: #fff;
            color: #333;

            .bookDetails {
                font-weight: bold;
            }

            .inputTitle {
                width: 100%;

                .left {
                    float: left;
                    width: 47%;

                    .el-select {
                        width: 100%;
                    }
                }

                .right {
                    margin-left: 6%;
                    float: left;
                    width: 47%;

                    .date {
                        width: 100%;
                    }
                }
            }
        }

        #footBox {
            width: 100%;
            height: 350px;
            background: white;
        }

        #footer {
            margin-left: 43%;
            height: 200px;

            .el-button {
                float: left;
                margin-top: 100px;
            }
        }

        body > .el-container {
            margin-bottom: 40px;
        }
    }
</style>